#pragma once

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_runner
{
    using namespace ns_log;
    using namespace ns_util;

    class runner
    {
        static void SetProcLimit(int cpu_limit, int mem_limit)
        {
            struct rlimit _cpu;
            _cpu.rlim_max = RLIM_INFINITY;
            _cpu.rlim_cur = cpu_limit;
            setrlimit(RLIMIT_CPU, &_cpu);

            struct rlimit _mem;
            _mem.rlim_max = RLIM_INFINITY;
            _mem.rlim_cur = mem_limit * 1024;
            setrlimit(RLIMIT_AS, &_mem);
        }

    public:
        runner() {}

        /*
        1.run返回值为信号量
            < 0 为内部错误
            > 0 为可执行程序收到的信号
            = 0 为程序运行成功
        */
        static int run(const std::string &file_name, int _cpu_limit, int _mem_limit) // mem_limit单位为KB
        {
            std::string _execute = PathUtil::Exe(file_name);
            std::string _stdin = PathUtil::Stdin(file_name);
            std::string _stdout = PathUtil::Stdout(file_name);
            std::string _stderr = PathUtil::Stderr(file_name);

            umask(0);
            int _stdin_fd = open(_stdin.c_str(), O_CREAT | O_RDONLY, 0644);
            int _stdout_fd = open(_stdout.c_str(), O_CREAT | O_WRONLY, 0644);
            int _stderr_fd = open(_stderr.c_str(), O_CREAT | O_WRONLY, 0644);
            if (_stdin_fd < 0 || _stdout_fd < 0 || _stderr_fd < 0)
            {
                LOG(Error) << "运行所需文件打开失败" << "\n";
                return -1;
            }

            pid_t pid = fork();
            if (pid < 0)
            {
                close(_stdin_fd);
                close(_stdout_fd);
                close(_stderr_fd);
                LOG(Error) << "运行程序创建失败" << "\n";
                return -2;
            }
            else if (pid == 0)
            {
                dup2(_stdin_fd, 0);
                dup2(_stdout_fd, 1);
                dup2(_stderr_fd, 2);

                SetProcLimit(_cpu_limit, _mem_limit);
                execl(_execute.c_str(), _execute.c_str(), nullptr);
                exit(1);
            }
            close(_stdin_fd);
            close(_stdout_fd);
            close(_stderr_fd);
            int status;
            waitpid(pid, &status, 0);
            LOG(Info) << "运行成功: " << (status & 0x7f) << "\n";
            return status & 0x7f;
        }

        ~runner() {}
    };

}